/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.emergency.bean.MaterialCheckResultView;
import com.koron.emergency.domain.EmergencyMaterial;
import com.koron.emergency.service.api.EmergencyMaterialService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "emergencyMaterial",description = "应急物资接口类")
@RestController
@RequestMapping("/emergencyMaterial")
public class EmergencyMaterialController {
    private final static Logger log = LoggerFactory.getLogger(EmergencyMaterialController.class);

    @Autowired
    private EmergencyMaterialService service;

    @Autowired
    private Util util;

    @ApiOperation("保存应急物资接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialType", value = "物资分类",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "物资名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialParameter", value = "规格参数",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "reserveQuota", value = "储备定额",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "existingQuantity", value = "现有数量",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "place", value = "存放地点",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "quantityUnit", value = "数量单位",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "storageTime", value = "入库时间",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "expirationTime", value = "过期时间",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "storageYear", value = "储备年限，0-10单位年",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "status", value = "物资状态，0正常，1异常",  dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "manager", value = "责任人code_单位code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "managerName", value = "责任人名称_单位名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkManager", value = "检查责任人code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "checkManagerName", value = "检查责任人名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "unitPrice", value = "单价",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "totalPrice", value = "总价",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "keepFiles", value = "要保留的附件，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "delFiles", value = "要删除的附件地址，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pdfKeepFiles", value = "要保留的pdf附件，多个之间用，分开",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pdfDelFiles", value = "要删除的pdf附件地址，多个之间用，分开",  dataType = "String",paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    @Log(title = "保存应急物资", businessModule = "应急物资", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore EmergencyMaterial bean,
                                     @RequestParam(required = false) final String keepFiles,@RequestParam(required = false) final String delFiles,
                                     @RequestParam(required = false) final String pdfKeepFiles,@RequestParam(required = false) final String pdfDelFiles,
                                     @RequestParam(required = false) final MultipartFile[] files){
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        bean.setUpdateTime(new Date());
        return service.save(bean,keepFiles,delFiles,pdfKeepFiles,pdfDelFiles,files);
    }

    @ApiOperation("删除应急物资接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "应急物资id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    @Log(title = "删除应急物资", businessModule = "应急物资", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteEmergency(@RequestParam final String id){

        return service.delete(id);
    }

    @ApiOperation("查询应急物资详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "应急物资id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<EmergencyMaterial> details(@RequestParam final String id){

        return service.queryOne(id);
    }

    @ApiOperation("应急物资列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "物资名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialType",value = "物资类型",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<EmergencyMaterial>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String materialType,
                                                         @RequestParam(required = false) String keyword,@RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<EmergencyMaterial>>msg= service.list(corpCode, name,materialType, start, pageSize,keyword);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("导出应急物资")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "物资名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "materialType",value = "物资类型",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/export.htm",method = RequestMethod.GET)
    public HttpEntity<?> export(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String materialType){
        Map<String,Object> map=new HashMap<>();
        MessageBean<DataBean<EmergencyMaterial>> msg=service.list(corpCode, name,materialType, null, null,null);
        if (msg.getData()!=null){
            map.put("data",msg.getData().getList());
        }
        File targetFile = new File("static/excel/emergencyMaterial.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/emergencyMaterial.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Excel.createFile("导出应急物资列表",targetFile, "emergencyMaterial.btl",map);
    }

    @ApiOperation("查看应急物资二维码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "应急物资id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/matrixToImage.htm",method = RequestMethod.POST)
    public MessageBean<?> MatrixToImage(String id){
        return  service.MatrixToImage(id);
    }

    @ApiOperation("应急物资-检查记录列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialId",value = "物资id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryCheckList.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<MaterialCheckResultView>> queryCheckList( @RequestParam final String materialId,
                                                         @RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<MaterialCheckResultView>>msg= service.queryCheckList(materialId, start, pageSize);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }


    @ApiOperation("下载模板")
    @RequestMapping(value = "/exportTemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportExcelTemplate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/emergencyMaterialTemplate.xlsx");
        try {
            InputStream initialStream = getClass().getClassLoader().getResourceAsStream("static/excel/emergencyMaterialTemplate.xlsx");
            FileUtils.copyInputStreamToFile(initialStream, targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Excel.createFile("应急物质台账导入模板", targetFile, "default.btl", map);
    }

    @ApiOperation("导入应急物质列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "上传的excel文件", required = true, paramType = "query", dataType = "file")
    })
    @RequestMapping(value = "/importExcel.htm", method = RequestMethod.POST)
    public MessageBean<?> importExcel(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode, String corpCode,
                                      @RequestParam(required = true) final MultipartFile file) {

        if (null == user) {
            //用于解决postman测试文件上传试的登陆问题
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0) {
                user = staffBeanList.get(0);
            }
        }
        MessageBean<?> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        if (null == file) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("未上传文件");
            return msg;
        }
        StaffBean finalUser = user;
        return ADOConnection.runTask(factory -> service.importExcel(factory, finalUser, corpCode, file), MessageBean.class);
    }

}
